<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>数据获取</title>
    <script src="https://unpkg.com/vue@2.7.7/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router@3.6.5/dist/vue-router.js"></script>
  </head>
  <body>
    <!-- 1 导航完成后获取数据 -->
    <div id="app1" style="border: 1px dashed red;margin-bottom: 2px;">
      <router-link to="/post">to /post</router-link><br />
      <router-view></router-view>
    </div>
    <!-- 2 在导航完成前获取数据 -->
    
    <script type="text/javascript">
      // 1 导航完成后获取数据
      const Post = {
        template: `
          <div class="post">
            <div v-if="loading" class="loading">Loading...</div>
            <div v-if="error" class="error">{{error}}</div>
            <div v-if="post" class="post">
              <h2>{{post.title}}</h2>
              <p>{{post.body}}</p>
            </div>
          </div>
        `,
        data() {
          return {
            loading: false,
            error: null,
            post: null
          }
        },
        created() {
          // 组件创建完后获取数据，
              // 此时 data 已经被 observed 了
          this.fetchData()
        },
        watch: {
          // 如果路由有变化，会再次执行该方法
          '$route': 'fetchData'
        },
        methods: {
          fetchData () {
            this.error = this.post = null
            this.loading = true
            // replace getPost with your data fetching util / API wrapper
            /* getPost(this.$route.params.id, (err, post) => {
              this.loading = false
              if (err) {
                this.error = err.toString()
              } else {
                this.post = post
              }
            }) */
            this.loading = false
            this.post = {title: 'title1', body: 'body1'}
            console.log(this.post, "first post")
            setTimeout("this.loading = false;this.post = {title: 'title2', body: 'body2'};console.log(this.post, \"second post\")", 2000)
          }, 
          getPost () {
            this.loading = false
            this.post = {title: 'title1', body: 'body1'}
            console.log(this.post, "third post")
          }
        }
      }
      
      const router = new VueRouter({
        routes: [
          {
            path: '/post', 
            component: Post
          }
        ]
      })
      
      new Vue({
        el: '#app1',
        router
      })

      // 2 在导航完成前获取数据
      
    </script>
  </body>
</html>